package com.qf.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Objects;
import java.util.Properties;

public class DBUtils {
    //声明数据源对象
    private static DruidDataSource ds;
    //声明本地线程变量
    private static ThreadLocal<Connection> THREAD_LOCAL = new ThreadLocal<>();

    //需要在静态代码块中给数据源ds赋值，需要读取数据库的配置文件
    static {
        try {
            InputStream inputStream = DBUtils.class.getResourceAsStream("/db.properties");
            // 把输入流中的数据读取到properties对象中
            Properties properties = new Properties();
            properties.load(inputStream);
            //给ds赋值
            ds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //静态方法，获取连接对象的方法
    public static Connection getConnection() {
        //从THREAD_LOCAL中获取连接对象
        Connection connection = THREAD_LOCAL.get();
        // 如果连接对象是null 就需要从数据源获取连接对象
        if (Objects.isNull(connection)){
            try {
                connection = ds.getConnection();
                // 获取到的连接对象放入THREAD_LOCAL中
                THREAD_LOCAL.set(connection);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return connection;
    }
    //开启事务
    public static void begin(){
        Connection connection = getConnection();
        if (Objects.nonNull(connection)){
            try {
                connection.setAutoCommit(false);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    //提交事务
    public static void commit(){
        Connection connection = getConnection();
        if (Objects.nonNull(connection)){
            try {
                connection.commit();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                //在finally中关闭资源
                closeAll(connection);
            }
        }
    }
    //回滚事务的方法
    public static void rollback(){
        Connection connection = getConnection();
        if (Objects.nonNull(connection)){
            try {
                connection.rollback();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                closeAll(connection);
            }
        }
    }
    //关闭资源的方法
    public static void closeAll(Connection connection){
        if (Objects.nonNull(connection)){
            try {
                connection.close();
                //关闭资源后，把连接对象从THREAD_LOCAL中移除
                THREAD_LOCAL.remove();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
